package com.xinqi.common.third.checkarea;

import com.alibaba.fastjson.JSONObject;
import com.xinqi.common.third.checkarea.config.ApiConfig;
import com.xinqi.common.third.checkarea.util.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Slf4j
public class CheckArea {

    public static Boolean checkPhoneArea(String phone) {
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + ApiConfig.AppCode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", phone);
        try {
            HttpResponse response = HttpUtils.doGet(ApiConfig.MOBILE_HOST, ApiConfig.MOBILE_PATH, "GET", headers, querys);
            String json = EntityUtils.toString(response.getEntity());
            if (json.contains("上海")) {
                return false;
            } else {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return true;
        }
    }

    public static Boolean checkIpArea(String ip) {
        // 【5】拼接请求链接
        String urlSend = ApiConfig.IP_HOST + ApiConfig.IP_PATH + "?ip=" + ip;
        try {
            URL url = new URL(urlSend);
            HttpURLConnection httpURLCon = (HttpURLConnection) url.openConnection();
            // 格式Authorization:APPCODE (中间是英文空格)
            httpURLCon.setRequestProperty("Authorization", "APPCODE " + ApiConfig.AppCode);
            int httpCode = httpURLCon.getResponseCode();
            if (httpCode == 200) {
                String json = read(httpURLCon.getInputStream());
                if (json.contains("上海")) {
                    return false;
                } else {
                    return true;
                }
            } else {
                Map<String, List<String>> map = httpURLCon.getHeaderFields();
                String error = map.get("X-Ca-Error-Message").get(0);
                if (httpCode == 400 && "Invalid AppCode `not exists`".equals(error)) {
                } else if (httpCode == 400 && "Invalid Url".equals(error)) {
                } else if (httpCode == 400 && "Invalid Param Location".equals(error)) {
                } else if (httpCode == 403 && "Unauthorized".equals(error)) {
                } else if (httpCode == 403 && "Quota Exhausted".equals(error)) {
                } else if (httpCode == 403 && "Api Market Subscription quota exhausted".equals(error)) {
                } else {
                }
                return true;
            }
        } catch (MalformedURLException e) {
        } catch (UnknownHostException e) {
        } catch (Exception e) {
        }
        return true;
    }

    /**
     * 根据IP获取地址信息
     *
     * @param ip
     * @return
     */
    public static String getLocationByIp(String ip) {
        String location = StringUtils.EMPTY;
        if (StringUtils.isEmpty(ip)) {
            return location;
        }
        String urlSend = ApiConfig.IP_HOST + ApiConfig.IP_PATH + "?ip=" + ip;
        try {
            URL url = new URL(urlSend);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestProperty("Authorization", "APPCODE " + ApiConfig.AppCode);
            int httpCode = connection.getResponseCode();
            if (httpCode == 200) {
                location = read(connection.getInputStream());
                location = getResult(location);
            }
        } catch (Exception e) {
            log.error("根据IP获取地址信息异常信息:{}", e.getMessage());
        }
        return location;
    }

    private static String getResult(String location) {
        JSONObject jsonObject = JSONObject.parseObject(location);
        Integer code = jsonObject.getInteger("code");
        if (Objects.equals(100, code)) {
            return jsonObject.getString("result");
        } else {
            return jsonObject.getString("message");
        }
    }

    /*
     * 读取返回结果
     */
    private static String read(InputStream is) throws IOException {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = br.readLine()) != null) {
            line = new String(line.getBytes(), "utf-8");
            sb.append(line);
        }
        br.close();
        return sb.toString();
    }

}
